package com.demo.tools;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

import org.apache.struts2.ServletActionContext;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;




public class StaticFreemarker {
	
	/**                                               
	 * 初始化模板引擎                                 
	 *                                                
	 * @param ftl 模板名称                            
	 * @param htmlpath 需要生成html页面的相对跟路径地址 
	 * @param htmlName 需要生成html页面的名称         
	 * @param map 模板中需要的参数集合                
	 * @param relativePath 模板相对于根路径的相对路径 
	 * @throws IOException                           
	 * @throws TemplateException                     
	 */       
	@SuppressWarnings("unchecked")                                                  
	public void init(String ftlPath, String ftlName,String htmlpath, String htmlName, Map map, String relativePath)     
	        throws IOException, TemplateException {                                    
	    Configuration freemarkerCfg = new Configuration();   
	    String path = ServletActionContext.getRequest().getSession().getServletContext().getRealPath(File.separator);
		   
	    freemarkerCfg.setDirectoryForTemplateLoading(new File(path+ftlPath));
	    
	    
	    
	    freemarkerCfg.setServletContextForTemplateLoading(ServletActionContext.getServletContext(), "/" + relativePath);                          
	    freemarkerCfg.setEncoding(Locale.getDefault(), "UTF-8");   
	    Template template = freemarkerCfg.getTemplate(ftlName);     
		  
	    //new org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer().setTemplateLoaderPath("");
	    
	    template.setEncoding("UTF-8");                                                   
	     
	    //判断生成的html路径是否存在
	    File htmlDirFile = new File( path+htmlpath);
	    if(!htmlDirFile.exists()){
	    	htmlDirFile.mkdirs();
	    }
	    
	    File htmlFile = new File(path +htmlpath+ htmlName);                                      
	    Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));                            
	    template.process(map, out);                                                 
	    out.flush();                                                                
	    out.close();                                                                
	}                                                                               

}
